package cn.xu.bookstore.user.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import cn.xu.bookstore.user.domain.User;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter(
		urlPatterns = { 
				"/LoginFilter", 
				"/jsps/order/*", 
				"/jsps/cart/*"
		}, 
		servletNames = { 
				"OrderServlet", 
				"CartServlet"
		})
public class LoginFilter implements Filter {

   private FilterConfig fConfig ;
	public void destroy() {}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		/*
		 * 判断session是否存在 如果不存在则 拦截否则放行
		 */
		HttpServletRequest req = (HttpServletRequest)request;
		User user = (User)req.getSession().getAttribute("session_user");
		
		if(user == null){
			req.setAttribute("msg", "你还没有登录请登录");
			req.getRequestDispatcher("/jsps/user/login.jsp").forward(req, response);
			
		}else{
			chain.doFilter(request, response);
		}
		
		
	}


	public void init(FilterConfig fConfig) throws ServletException {
		this.fConfig = fConfig;
	}

}
